<script setup>
import { ref, watch } from 'vue'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import { useUserStore } from '@/stores'
import {
  adminQueryVolunteerByIdService,
  adminUpdateVolunteerService
} from '@/api/volunteer.js'
const props = defineProps({
  editId: {
    type: Number
  },
  getVolunteerList: {
    type: Function
  }
})

const userStore = useUserStore()
const open = ref(false)
const confirmLoading = ref(false)
const showModal = () => {
  open.value = true
}
const volunteerInfo = ref()
const getVolunteerInfo = async (id) => {
  const response = await adminQueryVolunteerByIdService(id)
  volunteerInfo.value = response.data.data
  const backendTimeData = [
    volunteerInfo.value.beginTime,
    volunteerInfo.value.endTime
  ]
  timeStorage.value = backendTimeData.map((time) =>
    dayjs(time, 'YYYY-MM-DD HH:mm:ss')
  )
  timeStorage2.value = dayjs(volunteerInfo.value.registrationDeadline)
  //图片回显
  if (volunteerInfo.value.eventPhoto) {
    fileList.value = [
      {
        uid: '-1', // 唯一标识符，必须为字符串
        name: 'picture.png', // 文件名称
        status: 'done', // 文件状态，表示已经上传完成
        url: volunteerInfo.value.eventPhoto // 文件地址
      }
    ]
    previewImage.value = volunteerInfo.value.eventPhoto
  }
}

// 监听 id 变化
watch(
  () => props.editId,
  (newId) => {
    getVolunteerInfo(newId) // id 变化时重新发起请求
    console.log('editId changed:', newId)
  }
)
defineExpose({ showModal })

const UpdateVolunteer = async () => {
  // 表单验证
  if (!volunteerInfo.value.activityName) {
    message.error('请填写志愿活动名称')
    return
  }
  if (!volunteerInfo.value.organization) {
    message.error('请填写发布组织')
    return
  }
  if (!volunteerInfo.value.activityLocation) {
    message.error('请填写活动地点')
    return
  }
  if (!volunteerInfo.value.linkman) {
    message.error('请填写联系人')
    return
  }
  if (!volunteerInfo.value.contact) {
    message.error('请填写联系方式')
    return
  }
  if (!volunteerInfo.value.beginTime || !volunteerInfo.value.endTime) {
    message.error('请选择活动时间')
    return
  }
  if (!volunteerInfo.value.recruitNumber) {
    message.error('请填写招募人数')
    return
  }
  if (!volunteerInfo.value.recruitmentPositions) {
    message.error('请填写招募岗位')
    return
  }
  if (!volunteerInfo.value.enrollmentRestrictions) {
    message.error('请填写报名限制')
    return
  }
  if (!volunteerInfo.value.eventDescription) {
    message.error('请填写活动简介')
    return
  }
  if (!volunteerInfo.value.eventContent) {
    message.error('请填写活动内容')
    return
  }
  if (!volunteerInfo.value.eventPhoto) {
    message.error('请上传活动图片')
    return
  }
  volunteerInfo.value.tag = volunteerInfo.value.tag.toString()
  const res = await adminUpdateVolunteerService(volunteerInfo.value)
  if (res.data.code === 1) {
    message.success('更新成功')
    props.getVolunteerList()
    open.value = false
  } else {
    message.error('更新失败')
  }
}
//时间选择器相关
// 禁用当前时间之前的日期和时间
const disabledDate = (current) => {
  return current && current < dayjs().startOf('day')
}

const disabledTime = (current) => {
  if (!current) return {}
  const now = dayjs()
  if (current.isSame(now, 'day')) {
    return {
      disabledHours: () => Array.from({ length: now.hour() }, (_, i) => i),
      disabledMinutes: () =>
        now.hour() === current.hour()
          ? Array.from({ length: now.minute() }, (_, i) => i)
          : [],
      disabledSeconds: () => []
    }
  }
  return {}
}
// 时间选择器变化事件
const timeStorage = ref([])
const handleTimeChange = (value) => {
  if (Array.isArray(value)) {
    volunteerInfo.value.beginTime = dayjs(value[0]).format(
      'YYYY-MM-DD HH:mm:ss'
    )
    volunteerInfo.value.endTime = dayjs(value[1]).format('YYYY-MM-DD HH:mm:ss')
  }
}
const timeStorage2 = ref(null)
const handleTimeChange2 = (value) => {
  timeStorage2.value = value
  volunteerInfo.value.registrationDeadline = value
    ? dayjs(value).format('YYYY-MM-DD HH:mm:ss')
    : ''
}

//----------图片上传相关------------
const fileList = ref([])
const headers = {
  adminToken: userStore.token
}
const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')
const loading = ref(false)
const handleCancel = () => {
  previewVisible.value = false
  previewTitle.value = ''
}
const handlePreview = async (file) => {
  previewVisible.value = true
  previewTitle.value =
    file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
}
const handleChange = (info) => {
  if (info.file.status === 'uploading') {
    loading.value = true
    return
  }
  if (info.file.status === 'done') {
    loading.value = false
    message.success(`${info.file.name} 文件上传成功！`)
    volunteerInfo.value.eventPhoto = info.file.response.data
    previewImage.value = info.file.response.data
  }
  if (info.file.status === 'error') {
    loading.value = false
    message.error('上传失败！')
  }
}
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('图片格式有误!')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小必须小于2MB!')
  }
  return isJpgOrPng && isLt2M
}
</script>
<template>
  <div v-if="volunteerInfo">
    <a-modal
      v-model:open="open"
      title="活动详情"
      width="50%"
      :confirm-loading="confirmLoading"
    >
      <h1 style="display: flex; justify-content: center">
        {{ volunteerInfo.activityName }}
      </h1>
      <div>
        <h2><b>活动基础信息</b></h2>
        <span>志愿活动名称</span>
        <a-input-group compact>
          <a-input
            v-model:value="volunteerInfo.activityName"
            style="width: 50%"
          />
        </a-input-group>
        <span>发布组织</span>
        <a-input-group compact>
          <a-input
            v-model:value="volunteerInfo.organization"
            style="width: 50%"
          />
        </a-input-group>
        <span>活动地点</span>
        <a-input-group compact>
          <a-input
            v-model:value="volunteerInfo.activityLocation"
            style="width: 50%"
          />
        </a-input-group>
        <span>联系人</span>
        <a-input-group compact>
          <a-input v-model:value="volunteerInfo.linkman" style="width: 30%" />
        </a-input-group>
        <span>联系方式</span>
        <a-input-group compact>
          <a-input v-model:value="volunteerInfo.contact" style="width: 30%" />
        </a-input-group>
        <span>志愿标签</span>
        <a-input-group compact>
          <a-input v-model:value="volunteerInfo.tag" style="width: 30%" />
        </a-input-group>
        <h2><b>志愿者招募详情</b></h2>
        <span>活动时间</span>
        <a-input-group compact>
          <a-range-picker
            v-model:value="timeStorage"
            style="width: 400px"
            :disabled-date="disabledDate"
            :disabled-time="disabledTime"
            :show-time="{
              hideDisabledOptions: true,
              defaultValue: [
                dayjs('00:00:00', 'HH:mm:ss'),
                dayjs('23:59:59', 'HH:mm:ss')
              ]
            }"
            format="YYYY-MM-DD HH:mm:ss"
            @change="handleTimeChange"
          />
        </a-input-group>
        <span>招募人数</span>
        <a-input-group compact>
          <a-input
            v-model:value="volunteerInfo.recruitNumber"
            class="site-input-right"
            style="width: 100px; text-align: center"
            placeholder="最多"
          />
        </a-input-group>
        <span>招募岗位</span>
        <a-input-group compact>
          <a-input
            v-model:value="volunteerInfo.recruitmentPositions"
            style="width: 50%"
          />
        </a-input-group>
        <h2><b>报名须知</b></h2>
        <span>报名限制</span>
        <a-input-group compact>
          <a-input
            v-model:value="volunteerInfo.enrollmentRestrictions"
            style="width: 50%"
          />
        </a-input-group>
        <span>报名截止时间</span>
        <a-input-group compact>
          <a-date-picker
            show-time
            placeholder="Select Time"
            v-model:value="timeStorage2"
            :disabled-date="disabledDate"
            :disabled-time="disabledTime"
            @change="handleTimeChange2"
          />
        </a-input-group>
        <h2><b>活动介绍</b></h2>
        <span>活动简介</span>
        <a-input-group compact>
          <a-input
            v-model:value="volunteerInfo.eventDescription"
            style="width: 60%"
          />
        </a-input-group>
        <span>活动内容</span>
        <h1></h1>
        <a-textarea
          v-model:value="volunteerInfo.eventContent"
          style="width: 60%"
          size="large"
          placeholder="请描述活动内容"
          allow-clear
        />
        <h2><b>活动图片</b></h2>
        <a-form-item label="">
          <a-upload
            v-model:file-list="fileList"
            :headers="headers"
            action="/aPi/web/admin/common/upload"
            list-type="picture-card"
            :before-upload="beforeUpload"
            @preview="handlePreview"
            @change="handleChange"
          >
            <div v-if="fileList.length < 1">
              <loading-outlined v-if="loading"></loading-outlined>
              <PlusOutlined />
              <div style="margin-top: 8px">上传</div>
            </div>
          </a-upload>
          <a-modal
            :open="previewVisible"
            :title="previewTitle"
            :footer="null"
            @cancel="handleCancel"
          >
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-item>
      </div>
      <a-space
        class="site-input-group-wrapper"
        direction="vertical"
        size="middle"
      >
      </a-space>
      <a-space wrap style="display: flex; justify-content: center">
        <a-button type="primary" block size="large" @click="UpdateVolunteer()">
          修改活动信息
        </a-button>
      </a-space>
      <template v-slot:footer> </template>
    </a-modal>
  </div>
</template>
<style lang="scss" scoped></style>
